package io.rocketman.transport.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.rocketman.transport.NetworkTransportException;
import io.rocketman.transport.channel.Channel;
import io.rocketman.transport.channel.handler.ProtocolHeaderChannelHandler;
import io.rocketman.transport.channel.handler.SerializeChannelHandler;
import io.rocketman.transport.netty.server.handler.NettyServerChannelHandler;
import io.rocketman.transport.server.AbstractPeriodicityFeedbackMachineStateServer;
import io.rocketman.transport.server.handler.ServerChannelHandler;

import java.net.InetSocketAddress;

/**
 * @author He Peng
 * @create 2018-05-25 2:22
 * @update 2018-05-25 2:22
 * @updatedesc : 更新说明
 * @see
 */
public class NettyServer extends AbstractPeriodicityFeedbackMachineStateServer {


    public NettyServer(InetSocketAddress localAddress) {
        super(localAddress);
    }

    @Override
    public void start(InetSocketAddress localAddress) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        final ProtocolHeaderChannelHandler channelHandler =
                new ProtocolHeaderChannelHandler(
                        new SerializeChannelHandler(
                                new ServerChannelHandler()));
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup , workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerChannelHandler(channelHandler));
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(localAddress).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void shutdown() {

    }

    @Override
    public void restart() {

    }

    @Override
    public void send(Object message) throws NetworkTransportException {

    }
}
